const db = require('../db');
const jwt = require('jsonwebtoken');

exports.authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: '未提供身份验证令牌' });
  }

  jwt.verify(token, process.env.JWT_SECRET || 'your_jwt_secret', (err, user) => {
    if (err) {
      return res.status(403).json({ message: '令牌无效或已过期' });
    }
    req.user = user;
    next();
  });
};

// 检查用户角色
exports.checkRole = (...roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({ message: '未经过身份验证' });
    }

    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ message: '没有访问权限' });
    }

    next();
  };
};

// 获取当前用户信息
exports.getCurrentUser = (req, res, next) => {
  if (!req.user) {
    return res.status(401).json({ message: '未经过身份验证' });
  }

  const sql = 'SELECT u.id, u.username, u.full_name, u.email, r.name as role FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?';
  db.get(sql, [req.user.id], (err, user) => {
    if (err) {
      return res.status(500).json({ message: '获取用户信息失败', error: err.message });
    }
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    req.currentUser = user;
    next();
  });
};